/*
 * @Author: silence
 * @Date: 2022-07-28 15:15:22
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-08-09 14:20:58
 * @Description: 多图上传
 */
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:image_picker/image_picker.dart';

import '../../../utils/permission/PermissionUtils.dart';
import '../res.dart';
import '../utils/Tool/MyTools.dart';
import '../utils/color/ColorUtils.dart';
import 'MyBottomSheet.dart';
import 'MyBottomSheetWidget.dart';
import 'MyImage.dart';
import 'MyLocalImage.dart';

class UpLoadPicsWidget extends StatefulWidget {
  /// 网络图片地址列表
  final List<String>? imgUrlList;

  /// item的宽高,默认88
  final double? itemHeight;
  final double? itemWidth;

  /// 最大图片数量,默认4个
  final int maxNum;

  /// 主轴上item之间的间距，默认12
  final double? spacing;

  /// 垂直轴上item之间的间距，默认12
  final double? crossSpacing;

  /// 自定义删除按钮
  final Widget? delBtnWidget;

  /// 自定义占位组件
  final Widget? placeholderWidget;

  /// 是否要切圆角
  final double? radius;

  /// 返回选择的图片结果
  /// imgPathList 图片地址
  final Function(List<String> imgPathList)? rebackResultFunc;

  const UpLoadPicsWidget(
      {Key? key,
      this.maxNum = 4,
      this.spacing,
      this.itemHeight,
      this.crossSpacing,
      this.itemWidth,
      this.rebackResultFunc,
      this.placeholderWidget,
      this.delBtnWidget,
      this.radius,
      this.imgUrlList})
      : super(key: key);

  @override
  State<UpLoadPicsWidget> createState() => _UpLoadPicsWidgetState();
}

class _UpLoadPicsWidgetState extends State<UpLoadPicsWidget> {
  List<String> _picList = [];

  double _itemHeight = 0;
  double _itemWidth = 0;

  // 图片文件
  late ImagePicker _picker = ImagePicker();

  // 选中更换的图片索引
  int? _changeIndex;

  @override
  void initState() {
    super.initState();

    _itemHeight = widget.itemHeight ?? 88;
    _itemWidth = widget.itemWidth ?? 88;

    if (widget.imgUrlList != null) {
      _picList = widget.imgUrlList!;
    }
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> children = [];

    // 先添加图片数组
    for (var i = 0; i < _picList.length; i++) {
      children.add(photoBtn(i));
    }

    // 如果图片还没有占满位置，就在后面添加一个默认按钮
    if (_picList.length < widget.maxNum) {
      children.add(defaultAddPhotoBtn());
    }

    return Wrap(
      spacing: widget.spacing ?? 12,
      runSpacing: widget.crossSpacing ?? 12,
      children: children,
    );
  }

  /// 默认添加按钮
  defaultAddPhotoBtn() {
    Widget contentWidget = Container(
      width: _itemWidth,
      height: _itemHeight,
      color: ColorUtils.color_248_248_250,
      alignment: Alignment.center,
      child: widget.placeholderWidget ??
          const MyLocalImage(
            Res.fqa_icon_add,
            width: 76,
            height: 76,
          ),
    );

    // 是否切圆角
    if (widget.radius != null && widget.radius! > 0) {
      contentWidget = ClipRRect(
          child: contentWidget,
          borderRadius: BorderRadius.circular(widget.radius!));
    }

    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        // 添加图片
        showBottomSheet();
      },
      child: contentWidget,
    );
  }

  /// 图片按钮
  photoBtn(int index) {
    late Widget imgWidget;
    String imgPath = _picList[index];

    if (!MyTools.stringIsEmpty(imgPath)) {
      if (imgPath.contains('https://') || imgPath.contains('http://')) {
        // 网络图片
        imgWidget = MyImage(
          imgPath,
          placeholderImgPath: Res.fqa_icon_add,
          // errorImgPath: 'imgs/common/img_zhanweitu2@3x.png',
          width: _itemWidth,
          height: _itemHeight,
        );
      } else {
        // 本地图片
        imgWidget = Image.file(
          File(imgPath),
          width: _itemWidth,
          height: _itemHeight,
          fit: BoxFit.cover,
        );
      }
    }

    Widget contentWidget = Container(
      width: _itemWidth,
      height: _itemHeight,
      color: ColorUtils.color_248_248_250,
      child: Stack(children: [
        imgWidget,
        Positioned(
            right: 0,
            top: 0,
            child: widget.delBtnWidget ??
                MyLocalImage(
                  Res.sys_icon_delete_black,
                  height: 18,
                  width: 18,
                  onclick: () {
                    // 删除图片
                    setState(() {
                      if (_picList.length > 0) {
                        _picList.removeAt(index);
                        if (widget.rebackResultFunc != null)
                          widget.rebackResultFunc!(_picList);
                      }
                    });
                  },
                ))
      ]),
    );

    // 是否切圆角
    if (widget.radius != null && widget.radius! > 0) {
      contentWidget = ClipRRect(
          child: contentWidget,
          borderRadius: BorderRadius.circular(widget.radius!));
    }

    return GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          // 重新选择图片
          _changeIndex = index;
          showBottomSheet();
        },
        child: contentWidget);
  }

  showBottomSheet() async {
    // List<String> items = ['相机', '相册'];
    // MyBottomSheet.show(
    //     context: context,
    //     child: MyBottomSheetWidget(
    //       itemList: items,
    //       tapSureSeletedFunc: (selectedIndex) async {
    //         if (selectedIndex == 0) {
    //           // 相机
    //           bool value = await PermissionUtils.permission_camera();
    //           if (value == false) return;
    //           _onToCamera();
    //           Navigator.pop(context);
    //         } else {
    //           // 相册
    //           bool value = await PermissionUtils.permission_photo();
    //           if (value == false) return;
    //           _onToAlbum();
    //           Navigator.pop(context);
    //         }
    //       },
    //     ));
    // 相册
    bool value = await PermissionUtils.permission_camera();
    if (value == false) return;
    _onToAlbum();
  }

  /// 拍摄照片
  Future<void> _onToCamera() async {
    final image = await _picker.pickImage(source: ImageSource.camera);
    if (image == null) return;
    handlerImage(image.path);
  }

  /// 从相册选取
  Future<void> _onToAlbum() async {
    final image = await _picker.pickImage(source: ImageSource.gallery);
    if (image == null) return;
    handlerImage(image.path);
  }

  /// 处理图片：压缩、裁剪等
  handlerImage(String path) async {
    // 压缩图片
    File file = await FlutterNativeImage.compressImage(path,
        quality: 50, percentage: 50);

    if (_changeIndex != null && _picList.length > _changeIndex!) {
      _picList[_changeIndex!] = file.path;
      _changeIndex = null;
    } else {
      _picList.add(file.path);
    }

    /// 更新图片
    setState(() {
      if (widget.rebackResultFunc != null) {
        widget.rebackResultFunc!(_picList);
      }
    });
  }
}
